package com.oocl.im.ui;

import com.oocl.im.action.impl.LogoutAction;
import com.oocl.im.action.impl.ChatAction;
import com.oocl.im.entity.Client;
import com.oocl.im.entity.Protocol;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.LineBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import com.oocl.im.action.impl.ShakeAction;
import com.oocl.im.constants.ClientMaintenance;
import com.oocl.im.eventbus.MemberBus;
import com.oocl.im.eventbus.RxBus;
import com.oocl.im.eventbus.ShakeBus;

public class ChatFrame extends JFrame implements ActionListener {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static JTextArea chatTa;
	// private JTextArea friendsArea;
	private static JList friendsTa;
	private JPanel pan;
	private static JButton allButton;
//	private static JList<String> list1;
	private static JTextField sendTf;
	private static JButton sendBtn;
	private static JButton shakeBtn;
//	private DefaultListModel<String> model;
	
	public ChatFrame() {
		pan = new JPanel();
		this.setSize(800, 600);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setLocationRelativeTo(null);
		init();
		addEvent();
		operateBus();
		shakeBus();
		memberBus();
	//	logout();
		this.setVisible(true);

	}

	private void init() {
		this.setLayout(new BorderLayout());
		JPanel panLeft = new JPanel(new BorderLayout());
		JPanel panRight = new JPanel(new BorderLayout());
		JPanel panLeftBottom = new JPanel(new BorderLayout());
		JPanel panBtnGroup = new JPanel(new BorderLayout());
		allButton = new JButton("All");

		chatTa = new JTextArea(10, 20);
		
//		model = new DefaultListModel<>();list1 = new JList<>(model);
//		list1 = new JList<>(model);
		friendsTa = new JList(ClientMaintenance.clientList.toArray());
		friendsTa.setPreferredSize(new Dimension(100,400));
//		model.removeAllElements();
//		for(int i = 0; i<ClientMaintenance.clientList.size(); i++) {
//		model.addElement(ClientMaintenance.clientList.get(i).toString());
//		}
		
//		list1.setPreferredSize(new Dimension(100, 400));
//		System.out.println("list1 的值: "+ list1);
//		Vector<String> vec = new Vector<String>();
		
		
//		friendsTa = new JList(ClientMaintenance.clientList.toArray());
//		for(Object i:ClientMaintenance.clientList){
//			vec.add((String) i);
//		}
	//	friendsTa = new JList(vec);

//		friendsTa.addListSelectionListener(new ListSelectionListener() {
//			@Override
//			public void valueChanged(ListSelectionEvent e) {
//				ClientMaintenance.currentChatUser = new Client(
//						(String) friendsTa.getSelectedValue());
//				System.out.println(ClientMaintenance.currentChatUser);
//				setTitle(ClientMaintenance.client.getAccount()+"正在和"+ClientMaintenance.currentChatUser.getAccount()+"聊天");
//			}
//		});
		
		friendsTa.addListSelectionListener(new ListSelectionListener() {
			@SuppressWarnings("unchecked")
			@Override
			public void valueChanged(ListSelectionEvent e) {
				ClientMaintenance.currentChatUser = new Client(
						((JList<String>) e.getSource()).getSelectedValue());
				System.out.println("currentChatUser is: "+ClientMaintenance.currentChatUser);
				setTitle(ClientMaintenance.client.getAccount()+"正在和"+ClientMaintenance.currentChatUser.getAccount()+"聊天");
			}
		});



		pan.setLayout(new BorderLayout());

		pan.add(allButton, BorderLayout.NORTH);
		pan.add(new JScrollPane(friendsTa), BorderLayout.CENTER);
//		pan.add(new JScrollPane(list1), BorderLayout.CENTER);

		//Border border = BorderFactory.createEtchedBorder();

		sendTf = new JTextField();
		sendBtn = new JButton("send");
		shakeBtn = new JButton("shake");

		sendTf.setFont(new Font("宋体", Font.BOLD, 18));
		sendTf.setForeground(Color.red);
		setTitle(ClientMaintenance.client.getAccount());
		chatTa.setFont(new Font("宋体", Font.BOLD, 18));
		chatTa.setForeground(Color.blue);
		panRight.add(pan, BorderLayout.CENTER);
		panLeft.add(new JScrollPane(chatTa), BorderLayout.CENTER);
		panLeft.add(panLeftBottom, BorderLayout.SOUTH);
		panRight.setBorder(new LineBorder(Color.red));

		this.add(panLeft, BorderLayout.CENTER);
		this.add(panRight, BorderLayout.EAST);
		panBtnGroup.add(shakeBtn, BorderLayout.NORTH);
		panBtnGroup.add(sendBtn, BorderLayout.SOUTH);
		panLeftBottom.add(sendTf, BorderLayout.CENTER);
		panLeftBottom.add(panBtnGroup, BorderLayout.EAST);
	}
	
	private void addEvent() {
		sendBtn.addActionListener(this);
		shakeBtn.addActionListener(this);
		allButton.addActionListener(this);
		
		this.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				int option = JOptionPane.showConfirmDialog(null, "Exit the system？",
						"Exit Reminder", JOptionPane.YES_NO_OPTION,
						JOptionPane.QUESTION_MESSAGE);
				Protocol protocol = null;
				if (option == JOptionPane.YES_OPTION) {
//					setVisible(false);
					LogoutAction action = new LogoutAction(ClientMaintenance.oos);
					action.execute(protocol);
					
				} else {
					System.out.println("取消退出");
				}
				
			}
		});

	}
	public void actionPerformed(ActionEvent e) {
		
		Protocol protocol = null;
		System.out.println(e.getActionCommand());
		switch (e.getActionCommand()) {
		case "send":
			DateFormat formDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String time = formDate.format(System.currentTimeMillis());
			ChatAction action = new ChatAction(ClientMaintenance.oos);
			String content = sendTf.getText();
			action.setContent(content);
			System.out.println("chat content is"+content);
			action.execute(protocol);
			sendTf.setText("");
			chatTa.append(time +"  "+ClientMaintenance.client.getAccount()+" say: "+content + "\n");
			break;
		case "shake":
			System.out.println("shake");
			new ShakeAction(ClientMaintenance.oos).execute(protocol);
			break;
		case "All":
			setTitle(ClientMaintenance.client.getAccount()+"正在跟所有人聊天");
			ClientMaintenance.currentChatUser = new Client("@all");
			break;
		}
	}

	private void operateBus() {
		RxBus.get().toFlowable(String.class)
				.map(new Function<Object, String>() {
					@Override
					public String apply(@NonNull Object o) throws Exception {
						return (String) o;
					}
				}).subscribe(new Consumer<String>() {
					@Override
					public void accept(@NonNull String othersBean)
							throws Exception {
						if (othersBean != null) {
							chatTa.setText(chatTa.getText()  + othersBean);
						}
					}
				});
	}

	private void memberBus() {
		RxBus.get().toFlowable(MemberBus.class)
				.map(new Function<Object, MemberBus>() {
					@Override
					public MemberBus apply(@NonNull Object o) throws Exception {
						return (MemberBus) o;
					}
				}).subscribe(new Consumer<MemberBus>() {
					@Override
					public void accept(@NonNull MemberBus list)
							throws Exception {
						if (list != null) {
							friendsTa.setListData(list.getList());
						}
					}
				});
	}

	private void shakeBus() {
		RxBus.get().toFlowable(ShakeBus.class)
				.map(new Function<Object, ShakeBus>() {
					@Override
					public ShakeBus apply(@NonNull Object o) throws Exception {
						return (ShakeBus) o;
					}
				}).subscribe(new Consumer<ShakeBus>() {
					@Override
					public void accept(@NonNull ShakeBus list) throws Exception {
						new Thread() {
							@Override
							public void run() {
								int x = getLocation().x;
								int y = getLocation().y;

								for(int i = 0; i < 10; i++){
								try{
								Point endPoint = new Point(x + 10, y + 10);
								setLocation(endPoint);
								Thread.sleep(100);
								endPoint = new Point(x - 10, y - 10);
								setLocation(endPoint);
								Thread.sleep(100);
								}
								catch(InterruptedException e){
								System.out.println("抖动异常");
								}
							}
								}
						}.start();// 启动新线程
					}
				});
	}
}
